package com.zhixi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhixi.common.R;
import com.zhixi.common.SharedVariablesCurrent;
import com.zhixi.dto.SetmealDto;
import com.zhixi.pojo.Category;
import com.zhixi.pojo.Dish;
import com.zhixi.pojo.Setmeal;
import com.zhixi.pojo.SetmealDish;
import com.zhixi.service.CategoryService;
import com.zhixi.service.SetmealDishService;
import com.zhixi.service.SetmealService;
import com.zhixi.mapper.SetmealMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangzhixi
 * @description 针对表【setmeal(套餐)】的数据库操作Service实现
 * @createDate 2022-07-10 15:59:29
 */
@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
        implements SetmealService {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSetmeal(SetmealDto setmealDto, HttpServletRequest request) {
        // 添加套餐,因为继承了Setmeal所以这里可以直接添加。
        this.save(setmealDto);

        // 添加套餐的菜品，到套餐跟菜品的关联表中去
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().peek((item) -> item.setSetmealId(String.valueOf(setmealDto.getId()))).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public Page<Setmeal> pageWithSetmealDto(int page, int pageSize, String name) {
        // 1、构造分页对象
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);

        // 2、构造查询对象
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.like(name != null, Setmeal::getName, name)
                .orderByDesc(Setmeal::getUpdateTime);
        setmealPage = setmealService.page(setmealPage, setmealQueryWrapper);

        // 3、处理数据
        List<Setmeal> setmealList = setmealPage.getRecords().stream().peek(item -> {
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null && category.getName() != null) {
                item.setCategoryName(category.getName());
            }
        }).collect(Collectors.toList());

        // 4、将数据重新设置到page对象中
        setmealPage.setRecords(setmealList);

        return setmealPage;
    }

    @Override
    public void updateStatus(Long[] id, int status, HttpServletRequest request) {
        List<Setmeal> dishes = new ArrayList<>();
        for (Long aLong : id) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(aLong);
            setmeal.setStatus(status);
            dishes.add(setmeal);
        }
        this.updateBatchById(dishes);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R<String> delWithSetmealDish(Long[] ids) {
        log.info("删除套餐：{}", ids);
        List<Setmeal> setmeals = setmealService.listByIds(Arrays.asList(ids));
        List<Long> delIds = new ArrayList<>();
        // 1、查看所选的套餐是是售卖状态，如果有，则不能删除
        for (Setmeal setmeal : setmeals) {
            if (setmeal.getStatus() == 1) {
                return R.error("所选套餐包含启售商品，不能删除");
            }
            // 记录要删除的套餐id
            delIds.add(setmeal.getId());
        }

        // 2、删除套餐
        delIds.forEach(id -> {
            setmealService.removeById(id);
            setmealDishService.remove(new LambdaQueryWrapper<SetmealDish>().eq(SetmealDish::getSetmealId, id));
        });
        return R.success("套餐删除成功");
    }

    @Transactional
    @Override
    public R<String> updateWithSetmealDish(Setmeal setmeal) {
        // 1、更新套餐
        setmealService.update(setmeal, null);
        // 2、删除套餐中的菜品列表
        LambdaQueryWrapper<SetmealDish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(SetmealDish::getSetmealId, setmeal.getId());
        setmealDishService.remove(dishQueryWrapper);
        // /3、添加套餐中的菜品列表
        List<SetmealDish> setmealDishList = setmeal.getDishList();
        if (setmealDishList != null && setmealDishList.size() > 0) {
            setmealDishService.saveBatch(setmealDishList);
        }
        return R.success("套餐修改成功");
    }

    @Override
    public List<Setmeal> getSetmealList(Long categoryId, Long status) {
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();

        List<Setmeal> setmealList = new ArrayList<>();
        if (categoryId != null) {
            setmealLambdaQueryWrapper
                    .eq(Setmeal::getCategoryId, categoryId)
                    .eq(Setmeal::getStatus, status)
                    .orderByDesc(Setmeal::getUpdateTime);

            setmealList = setmealService.list(setmealLambdaQueryWrapper);
        }

        return setmealList;
    }

    @Override
    public Setmeal getSetmeal(Long id) {
        // 1、查询套餐
        Setmeal setmeal = setmealService.getById(id);

        LambdaQueryWrapper<SetmealDish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(SetmealDish::getSetmealId, id);

        // 2、查询套餐中的菜品分类
        Category category = categoryService.getById(setmeal.getCategoryId());
        if (category != null && StringUtils.isNotBlank(category.getName())) {
            // 设置菜品分类名称
            setmeal.setCategoryName(category.getName());
        }

        // 3、查询套餐中的菜品列表
        List<SetmealDish> setmealDishList = setmealDishService.list(dishQueryWrapper);
        if (setmealDishList != null && setmealDishList.size() > 0) {
            // 添加套餐中的菜品列表
            setmeal.setDishList(setmealDishList);
        }
        return setmeal;
    }
}




